var core = require('core');
var db = core.db;
var send = core.send;

var add = function(req, res, next){

    var body = req.body;
    var SEND;
    var query = {
        openid : body.admin
    };

    var options = {
        upsert : true
    };

    db.schema.User.findOne(query, function(err, doc){
        if(err){
            console.error(err.code);
            SEND = new send(100001);
            res.send(SEND);
        }else{
            if(doc.subscribe != true){
                SEND = new send(100202);
                return res.send(SEND);
            };
            var query = {
                name : body.name
            };
            var address = body.address;
            body.address = {
                area : body.area.split(','),
                text : body.address
            };
            // body.personnel = [{
                // openid : body.admin,
                // level : 0,
                // recommend : body.recommend
            // }];
            delete body.admin;
            var Merchant = new db.schema.Merchant(body);
            Merchant.save(function(err, doc){
                if(err){
                    SEND = new send(100001);
                    res.send(SEND);
                }else{
                    SEND = new send(0);
                    SEND.docs = doc;
                    res.send(SEND);
                }
            });
        };
    });



};

module.exports = add;
